//
//  OwnerSignForNewStcFormVC.swift
//  ezyform
//
//  Created by Moennig Q on 7/5/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//
import UIKit
import Foundation
import AVFoundation
class OwnerSignForNewStcFormVC: BaseViewController {
    weak var model: PVDDetailModel!
    let customView = OwnerSignForNewStcFormView(customBackToPreFlag: true)
    //前置摄像头拍照
    var session: AVCaptureSession?
    var output: AVCapturePhotoOutput?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.model = JobDetailModelHelper.shared.jobDetailModel
        initUI()
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if authStatus == .authorized { /****已授权，可以打开相机且installer或owner才自拍****/
            setupInputOutput()
        }
    }
    func initUI(){
        //title
        self.view = self.customView
        self.customView.backToPreBtn.addTarget(self, action: #selector(backToPreVieController), for: UIControl.Event.touchUpInside)
        self.customView.setTitleInfo(SignatureType.Owner.rawValue + " Signature")
        
        self.customView.setData(model,asWitnessFlag: APPConfig.loginInfo.currentSignatureType == .Owner ? false: true)
        self.customView.operateBtnClousure = {[weak self] in
            guard let strongSelf = self else { return  }
            strongSelf.toSaveSignature()
        }
    }
    func toWitnessVC(){
        let vc = WitnessSignForNewStcFormVC()
        self.navigationController?.pushViewController(vc, animated: false)
    }
    @objc func backToPreVieController() {
        Tool().showAlertViewWithTwoBtns(message: R.string.localizable.pvdDetailSignaturesSignatureBackfromsignTip(),  yesClosure: {[weak self] in
            self?.navigationController?.popViewController(animated: false)
        })
    }
    func toSaveSignature(){
        self.customView.endEditing(true)
        guard let model = self.model else { return  }
        //检查是否已签名
        if !self.customView.signView.signaturedFlag {
            Tool().showAlertViewWithOneBtn(message: R.string.localizable.pleaseSignBeforeSaving())
            return
        }
        
        if model.owner_address.type.lowercased() != "individual" {
            self.customView.signedTextfield.checkTextIfValid()
            if self.customView.signedTextfield.validStatus.value == .invalid{
                return
            }
        }
        if let _ = self.output,let _ = self.session {
            let settings = AVCapturePhotoSettings()
            output!.capturePhoto(with: settings, delegate: self)
        }else{
           self.saveSignature()
        }
    }
    func saveSignature(_ selfieData: Data? = nil){
        //owner的selfie ，转换为竖屏方向
        if let data = selfieData {
            let signSelfiData = MediaUtil().normalizedImage(data)
            let originImageData = MediaUtil().resetSizeOfImageData(source_image: UIImage(data: signSelfiData),maxSize: 100)
            APPConfig.loginInfo.signatureInfoModel.owner_signature_selfie = originImageData
        }
        let image = self.customView.signView.getSignature()
        if let imageData = image.pngData() {
            let ownerSignedData = NSData(data: imageData)
            var ownerSignedName = ""
            //非individual客户，需要输入owner name
            if self.model.owner_address.type.lowercased() != "individual"{
                ownerSignedName = self.customView.signedTextfield.textField.text ?? ""
            }else{//individual使用type name
                ownerSignedName = self.model.owner_address.type_name
            }
            let ownerSignedAtTime = DateUtil().getCurrentDatetime()
            //pvd id
            APPConfig.loginInfo.signatureInfoModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
            //owner
            APPConfig.loginInfo.signatureInfoModel.owner_sign_imagedata = ownerSignedData
            APPConfig.loginInfo.signatureInfoModel.owner_signed_at = ownerSignedAtTime
            APPConfig.loginInfo.signatureInfoModel.owner_signed_name = ownerSignedName
            if APPConfig.loginInfo.currentSignatureType == .Owner {//Owner自己签名
                self.toWitnessVC()
            }else{
                self.dealForOwnerAsWitness()
            }
        }else{
            Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.signatures.signature.save.faild", comment: ""))
        }
    }
    //处理owner作为witness的签名保存
    func dealForOwnerAsWitness(){
        self.customView.operateBtn.disableBtn()//此处是防止多次点击saveBtn，重复提交签名导致错误提示（NEWGD-914）
        //签名图片
        switch APPConfig.loginInfo.currentSignatureType {
        case .Installer:
            //installer签名协议中引用的Job 信息数据也传递到后台
//            APPConfig.loginInfo.signatureInfoModel.statement_input_param_all = InstallationDetailVCHelper.shared.getAllRequiredJsonForSign(self.model, signTypes: [.Installer,.Owner])
            APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_signature = APPConfig.loginInfo.signatureInfoModel.owner_sign_imagedata
            APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_date = APPConfig.loginInfo.signatureInfoModel.owner_signed_at
            APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_name = APPConfig.loginInfo.signatureInfoModel.owner_signed_name
            //owner的witness
            APPConfig.loginInfo.signatureInfoModel.witness_sign_imagedata = APPConfig.loginInfo.signatureInfoModel.installer_sign_imagedata
            APPConfig.loginInfo.signatureInfoModel.witness_signed_at = APPConfig.loginInfo.signatureInfoModel.installer_signed_at
            APPConfig.loginInfo.signatureInfoModel.witness_signed_name = self.model.signatures.installer_full_name
        case .Designer:
            //designer签名协议中引用的Job 信息数据也传递到后台
//            APPConfig.loginInfo.signatureInfoModel.statement_input_param_all = InstallationDetailVCHelper.shared.getAllRequiredJsonForSign(self.model, signTypes: [.Designer,.Owner])
            APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_signature = APPConfig.loginInfo.signatureInfoModel.owner_sign_imagedata
            APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_date = APPConfig.loginInfo.signatureInfoModel.owner_signed_at
            APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_name = APPConfig.loginInfo.signatureInfoModel.owner_signed_name
            //owner的witness
            APPConfig.loginInfo.signatureInfoModel.witness_sign_imagedata = APPConfig.loginInfo.signatureInfoModel.designer_sign_imagedata
            APPConfig.loginInfo.signatureInfoModel.witness_signed_at = APPConfig.loginInfo.signatureInfoModel.designer_signed_at
            APPConfig.loginInfo.signatureInfoModel.witness_signed_name = self.model.signatures.designer_full_name
        case .InstallerAndDesiger:
            //installer，designer签名协议中引用的Job 信息数据也传递到后台
//            APPConfig.loginInfo.signatureInfoModel.statement_input_param_all = InstallationDetailVCHelper.shared.getAllRequiredJsonForSign(self.model, signTypes: [.Installer,.Designer,.Owner])
            //installer 的witness
            APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_signature = APPConfig.loginInfo.signatureInfoModel.owner_sign_imagedata
            APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_date = APPConfig.loginInfo.signatureInfoModel.owner_signed_at
            APPConfig.loginInfo.signatureInfoModel.installer_witness_signed_name = APPConfig.loginInfo.signatureInfoModel.owner_signed_name
            //Designer的witness
            APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_signature = APPConfig.loginInfo.signatureInfoModel.owner_sign_imagedata
            APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_date = APPConfig.loginInfo.signatureInfoModel.owner_signed_at
            APPConfig.loginInfo.signatureInfoModel.designer_witness_signed_name = APPConfig.loginInfo.signatureInfoModel.owner_signed_name
            //owner的witness
            APPConfig.loginInfo.signatureInfoModel.witness_sign_imagedata = APPConfig.loginInfo.signatureInfoModel.designer_sign_imagedata
            APPConfig.loginInfo.signatureInfoModel.witness_signed_at = APPConfig.loginInfo.signatureInfoModel.designer_signed_at
            APPConfig.loginInfo.signatureInfoModel.witness_signed_name = self.model.signatures.designer_full_name
            
        default:
            break
        }
        //上传签名
        InstallationSignatureService().setDataInfo(self).requestUploadSignature() { [weak self] in
            guard let strongSelf = self else { return  }
            InstallationSignatureService().setDataInfo(strongSelf).dealLocalSignatureByOwnerSave()//删除本地数据
            InstallationSignatureService().setDataInfo(strongSelf).backToDetailVC()
            InstallationDetailVCHelper.shared.cacheData()//缓存新数据，刷新detail界面的数据
            
        } faildClosure: {  (code, errMsg) in
            Tool().showErrorInfo(code,errMsg)
        }
    }
    //Get the device (Front or Back)
    func getDevice(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
        let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: position)
        let devices = deviceDiscoverySession.devices
        if devices.count > 0 {
            return devices[0]
        }
        return nil
    }
    func setupInputOutput(){
        if let camera = getDevice(position: .front) {
            do {
                self.session = AVCaptureSession()
                self.output = AVCapturePhotoOutput()
                guard let _ = self.session,let _ = output  else {
                    return
                }
                self.session!.beginConfiguration()
                //如果session包括AVCapturePhotoOutput对象，session会自动尝试启用wide-color，有些设备(iPad)并不支持activeFormat.supportedColorSpaces，这是个AVCaptureSession的坑
                self.session!.automaticallyConfiguresCaptureDeviceForWideColor = false
                let input = try AVCaptureDeviceInput(device: camera)
                if self.session!.canAddInput(input){
                    self.session!.addInput(input)
                }
                
                output!.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg] )], completionHandler: nil)
                session!.sessionPreset = .photo
                if session!.canAddOutput(output!){
                    session!.addOutput(output!)
                }
                self.session!.commitConfiguration()
            }catch{
                print(error)
            }
            
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let _ = self.session {
            DispatchQueue.global(qos:.background).async {
                self.session!.startRunning()
            }
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let _ = self.session {
            self.session!.stopRunning()
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }

}
extension OwnerSignForNewStcFormVC: AVCapturePhotoCaptureDelegate{
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let _ = self.session{
            self.session!.stopRunning()
        }
        
        if let _ = error{
            let errMsg = "Owner sign and can not take selfi, the reason: " + error!.localizedDescription
            AppLogHelper.shared.sendErrorLog(errMsg, errorType: ErrorType.Signature)
            self.saveSignature()
        }else{
            if let imageData = photo.fileDataRepresentation() {
                self.saveSignature(imageData)
            }else{
                let errMsg = "Owner sign and can not take selfi, the reason: photo.fileDataRepresentation() not working"
                AppLogHelper.shared.sendErrorLog(errMsg, errorType: ErrorType.Signature)
                self.saveSignature()
            }
        }
    }
}
